package com.sunday.common.core.utils;


import java.security.MessageDigest;

/**
 * SHA256 摘要算法工具类
 *
 * @author zsy
 * @since 2024/1/18
 */
public class SHA256Utils {

    /**
     * 利用java原生的摘要实现SHA256加密
     *
     * @param data
     * @return {@link String}
     */
    public static String getSHA256(String data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(data.getBytes("UTF-8"));
            return byte2Hex(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将byte转为16进制
     *
     * @param bytes
     * @return {@link String}
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

}